<template>
  <a-upload
    :file-list="fileListForUpload"
    :custom-request="handleUpload"
    @remove="handleRemove"
    @preview="handlePreview"
  >
  <template  #upload-button>
        <a-button type="primary"> 上传附件</a-button>
      </template>
  </a-upload>
</template>

<script setup lang="ts">
import { ref, watch, computed } from 'vue';
import { FileItem, Message } from '@arco-design/web-vue';
import { sysUploadFile } from '@/api/demand';

const props = defineProps<{

  modelValue: { fileName: string; filePath: string }[];
}>();

const emit = defineEmits<{
  (e: 'update:modelValue', value: { fileName: string; filePath: string }[]): void;
}>();

const fileList = ref<{ fileName: string; filePath: string }[]>([]);

watch(
  () => props.modelValue,
  (newValue) => {
    fileList.value = newValue;
  },
  { immediate: true }
);

const fileListForUpload = computed(() => {
  return fileList.value.map((file) => ({
    name: file?.fileName || '',
    url: file?.filePath,
    status: 'done',
  }));
});

const handleUpload = async (option: RequestOption) => {
  const { file } = option.fileItem;
   console.log(file)
  const formData = new FormData();
  formData.append('type', '1');
  formData.append('file', file);

  try {
    const response = await sysUploadFile(formData);
    console.log(response,'--response')
    const { fileName, url } = response as any;

    fileList.value.push({ fileName, filePath:url });
    emit('update:modelValue', fileList.value);
  } catch (error) {
    Message.error('文件上传失败');
  }
};

const handleRemove = (file: FileItem) => {
  const index = fileList.value.findIndex(
    (item) => item.fileName === file.name && item.filePath === file.url
  );
  if (index !== -1) {
    fileList.value.splice(index, 1);
    emit('update:modelValue', fileList.value);
  }
};

const handlePreview = (file: FileItem) => {
  window.open(file.url, '_blank');
};


</script>